#include <SDL/SDL.h>
#include <assert.h>
#include <unistd.h>
#include <SDL/SDL_image.h>

#define TARGET_DELAY 35

int quit = 0;

void blit_tiles(SDL_Surface *img, SDL_Surface *scr, int x_tile_offset = 0, const int tiles_per_row = 16) {
  SDL_Rect src, dest;

  src.x = x_tile_offset;
  src.w = 16;
  src.h = 16;
  dest.w = 16;
  dest.h = 16;
  for(int ii = 0; ii < img->h; ii += 16) {
    int i = ii / 16;
    int x = i % tiles_per_row;
    int y = i / tiles_per_row;

    src.y = ii;
    dest.x = 800 - 320 + x * 19;
    dest.y = 400 - 300 + y * 18;
    SDL_BlitSurface(img, &src, scr, &dest);
  }
}

int main(int argc, char **argv) {
  SDL_Surface *img, *scr;
  SDL_Event event;
  int x_tile_offset = 0;
  unsigned long last_ticks = 0;

  assert(SDL_Init(SDL_INIT_VIDEO) == 0);
  scr = SDL_SetVideoMode(800, 480, 32, SDL_HWSURFACE|SDL_ANYFORMAT|SDL_DOUBLEBUF);
  assert(scr);
  img = IMG_Load("hero2.tiles.png");
  assert(img);
  SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); //Ignore all mouse movements...

  blit_tiles(img, scr);
  SDL_Flip(scr);
  while(!quit) {
    unsigned long ticks = static_cast<unsigned long>(SDL_GetTicks());
    printf("ticks = %lu ∆ = %lu\n", ticks, ticks - last_ticks);
    last_ticks = ticks;
    while(SDL_PollEvent(&event) == 1 && quit == 0) {
      switch(event.type) {
      case SDL_QUIT:
	quit = 2;
	break;
      case SDL_MOUSEBUTTONDOWN:
      case SDL_MOUSEBUTTONUP:
	printf("button=%d state=%d x=$%04hX y=$%04hX\n", event.button.button, event.button.state, event.button.x, event.button.y);
	break;
      case SDL_KEYDOWN:
      case SDL_KEYUP:
	printf("state=%d sym=$%04X\n", event.key.state, event.key.keysym.sym);
	break;
      default:
	printf("event.type = $%x\n", (unsigned int)event.type);
      }
    }
    if(++x_tile_offset > img->w - 16) x_tile_offset = 0;
    blit_tiles(img, scr, x_tile_offset);
    SDL_Flip(scr);
    long new_delta = last_ticks + TARGET_DELAY - SDL_GetTicks();
    if(new_delta > 0) SDL_Delay(new_delta > TARGET_DELAY ? TARGET_DELAY : new_delta);
  }
  SDL_Quit();
  return 0;
}


// g++ square_display.cc -lSDL -lSDL_image -lpthread
